package com.shaoyu.spring.study.runner;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 请求上下文
 * @author: shaoyu1
 * @date: 2020/11/4 15:08:18
 */
public final class HandlerContext extends ConcurrentHashMap<String, Object> {
    protected static Class contextClass = HandlerContext.class;
    protected static final ThreadLocal<HandlerContext> threadLocal = InheritableThreadLocal.withInitial(()-> {
        try {
            return (HandlerContext)contextClass.newInstance();
        } catch (Throwable e) {
            return null;
        }
    });
    public static HandlerContext getCurrentContext() {
        HandlerContext context = threadLocal.get();
        return context;
    }
    public void set(String key, Object value) {
        if (value != null)
            put(key, value);
        else
            remove(key);
    }
    public void unset() {
        threadLocal.remove();
    }

    public void interrupted() {
        this.put("interrupted", true);
    }

    public void initInterruptedFlag() {
        this.put("interrupted", false);
    }

    public boolean isInterrupted() {
        return (Boolean)this.get("interrupted");
    }
}
